import { useMemo } from "react";
import CommonModal from "@/components/CommonModal";
import { Button } from "antd";
import QRCode from "qrcode.react";
import { getPxMm } from "@/utils/utils.jsx";
import BarCode from "./BarCode";
import styles from "./index.module.less";
import { getCurrentUser } from "@/utils/authority";

const sizeScale = getPxMm();

const formatRowTextArr = (width, value) => {
	//按照字节长度
	const len = Math.floor(width / 6);
	const newArr = [];
	if (value) {
		const rowArr = value.split("\n");
		rowArr.map(item => {
			if (item) {
				let str = "",
					num = 0;
				for (let i = 0; i < item.length; i++) {
					const zijie = item.charCodeAt(i) > 255 ? 2 : 1;
					if (num + zijie <= len) {
						str += item.charAt(i);
						num += zijie;
					} else {
						newArr.push(str);
						str = item.charAt(i);
						num = zijie;
					}
					if (i == item.length - 1) {
						newArr.push(str);
					}
				}
			} else {
				newArr.push("");
			}
		});
	}
	// console.log(len,newArr)
	return newArr;
};

//预览弹窗
const PreviewImg = ({ source, handleCancel }) => {

	//聚合数据源
	const polymerDataCopy = data => {
		const arr = [];
		Object.keys(data).map(item => {
			if (data[item] instanceof Object) {
				data[item].length &&
					data[item].map(child => {
						if (item == "table") {
							const arrHearder = child.value ? child.value.split("#") : ["", ""];
							arr.push({
								...child,
								type: item,
								left: (sizeScale * 100 * 50 * (child.left - 15)) / 40000 + 4,
								top: (sizeScale * 100 * 80 * child.top) / 64000,
								width: (sizeScale * 100 * 50 * child.width) / 40000,
								height: (sizeScale * 100 * 80 * child.height) / 64000,
								leftHeader: arrHearder[0],
								rightHeader: arrHearder[1]
							});
						} else {
							arr.push({
								...child,
								type: item,
								left: (sizeScale * 100 * 50 * (child.left - 15)) / 40000 + 4,
								top: (sizeScale * 100 * 80 * child.top) / 64000,
								width: (sizeScale * 100 * 50 * child.width) / 40000,
								height: (sizeScale * 100 * 80 * child.height) / 64000,
								value: child.value || child.fieldName
							});
						}
					});
				if (item == "uniqueCode") {
					arr.push({
						...data[item],
						type: item,
						left: (sizeScale * 100 * 50 * (data[item].left - 15)) / 40000 + 4,
						top: (sizeScale * 100 * 80 * data[item].top) / 64000,
						width: (sizeScale * 100 * 50 * data[item].width) / 40000,
						height: (sizeScale * 100 * 80 * data[item].height) / 64000,
						value: "525000000000000001"
					});
				}
			}
		});
		return arr;
	};

	const TemplateWithPadding = useMemo(() => {
		return polymerDataCopy(source ? JSON.parse(source) : "");
	}, [source]);

	const currentUuid = getCurrentUser()?.uuid

	//渲染item 主体部分
	const renderMainMsg = v => {
		const { type, width, height, value, id } = v;
		if (type == "customTexts") {
			//自定义文本框
			const arr = formatRowTextArr(width, value);
			return arr.map((item, index) => (
				<p key={`${item}${index}`} style={{ font: `${12}px monospace` }}>
					{item}
				</p>
			)); //id == 'c1' ? 20 : 12
		} else if (type == "customQrCodes") {
			//自定义二维码
			return <QRCode value={value} size={width} fgColor="#000000" />;
		} else if (type == "customBarCodes" || type == "uniqueCode") {
			//自定义条形码 （及唯一码）
			return (
				<BarCode
					value={["#goodsUniqueCode#", '#shopOrderNumber#'].includes(value) ? "88888888" : value}
					width={1.3}
					height={height}
					displayValue={true}
					className={styles.previewBarCodes}
				/>
			);
		} else if (type == "table") {
			const { data = [{ customId: "actual-only-one" }], percentLeft = 50, leftHeader, rightHeader, width } = v;
			return (
				<div style={{ width }}>
					<div style={{ display: "flex", flexWrap: "wrap", width: "100%", height: 14 }} key="headerTitle">
						<div style={{ width: `${percentLeft}%`, border: "1px solid #ccc" }}>{leftHeader}</div>
						<div style={{ width: `${100 - percentLeft}%`, border: "1px solid #ccc", borderLeft: "none" }}>{rightHeader}</div>
					</div>
					{data.map((item, index) => {
						return (
							<div style={{ display: "flex", flexWrap: "wrap", width: "100%", height: 66 }} key={item.customId}>
								<div style={{ width: `${percentLeft}%` }} className={styles.leftColumn}>
									{/* {item.leftValue} */}
								</div>
								<div style={{ width: `${100 - percentLeft}%` }} className={styles.rightColumn}>
									{/* {item.rightValue} */}
								</div>
							</div>
						);
					})}
				</div>
			);
		} else {
			// 用户定制模板字段大小
			const bigValueMap = {
				'722324': ['分拣框'],
				'727786': ['订单单多件'],
			}
			const littleBigValueMap = {
				'722324': ['用户简称', '款式编码', '商品编码', '货品总数', '订单单多件'],
				'726536': ['分拣框', '用户简称', '款式编码', '货品总数', '订单单多件'],
				'727786': ['用户简称', '分拣框', '商品编码', '货品总数'],
				'721261': ['用户简称', '商品编码', '订单单多件', '货品总数', '分拣框'],
			}
			if (bigValueMap[currentUuid]?.includes(value)) {
				return <div style={{ font: '18px monospace' }}>{value}</div>
			} else if (littleBigValueMap[currentUuid]?.includes(value)) {
				return <div style={{ font: '15px monospace' }}>{value}</div>
			}
			return value;
		}
	};

	return (
		<CommonModal
			title="预览"
			width="378px"
			height={sizeScale * 80 + 132}
			visible={true}
			onCancel={handleCancel}
			footer={[
				<Button key="previewClose" onClick={handleCancel}>
					关闭
				</Button>
			]}
		>
			<div
				style={{
					width: "100%",
					height: sizeScale * 80,
					display: "flex",
					justifyContent: "center",
					alignItems: "center",
					font: `12px monospace`,
					fontWeight: "bold"
				}}
			>
				<div
					style={{
						width: sizeScale * 50,
						height: "100%",
						background: "#FFFFFF",
						position: "relative",
						overflow: "hidden",
						boxShadow: "0px 0px 10px rgb(79 94 112 / 10%)"
					}}
				>
					{TemplateWithPadding.map(v => {
						if (v.type == "customQrCodes") {
							v.width = v.cellWidth * sizeScale * 3.6;
							v.height = v.width;
						}
						return (
							<div key={v.id} className={styles.dragItem} style={{ ...v, zIndex: v.addIndex, background: "#FFFFFF" }}>
								<div className={styles.renderMsg}>{renderMainMsg(v)}</div>
							</div>
						);
					})}
				</div>
			</div>
		</CommonModal>
	);
};

export default PreviewImg;
